<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择审批人"
    width="500px"
    :before-close="close"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-scrollbar max-height="calc(100vh - 350px)">
      <div style="width: 98%">
        <CustomForm
          ref="formRef"
          :formData="formData"
          :schemas="formSchemas"
          :rules="rules"
          :show-span="true"
          :label-width="120"
          size="default"
        />
      </div>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, h, reactive, ref, useTemplateRef } from 'vue'
import CustomForm from '@/components/form/CustomForm.vue'
import { IFormSchemas } from '@/type/table'
import { FormRules } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import SelectApproveUser from '../user/SelectApproveUser.vue'
import { IAllApproveUser } from '@/api/sys/userManage'

const formRef = useTemplateRef<typeof CustomForm>('formRef')

const emits = defineEmits(['submit'])

interface IApproveUser {
  approveUserInfo: Record<string, any>[]
}
const defaultData = {
  approveUserInfo: undefined,
}

const copyDefaultData = cloneDeep(defaultData)

const formData = reactive<IApproveUser>(defaultData)

const rules = reactive<FormRules<IApproveUser>>({
  approveUserInfo: [
    { required: true, message: '请选择审批人', trigger: 'change' },
  ],
})

const getUserParams = ref<IAllApproveUser>({})

const formSchemas = computed<IFormSchemas[]>(() => {
  return [
    {
      label: '审批人',
      prop: 'approveUserInfo',
      type: (props) => {
        return h(SelectApproveUser, {
          ...props,
          clearable: true,
          placeholder: '请选择审批人',
        })
      },
      componentProps: {
        ...getUserParams.value,
      },
    },
  ]
})

const dialogVisible = ref(false)

defineExpose({ show })

async function show(params: IAllApproveUser) {
  getUserParams.value = params
  dialogVisible.value = true
}

function close() {
  dialogVisible.value = false
  Object.assign(formData, copyDefaultData)
  formRef.value?.reset()
}

// 提交
async function submit() {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      emits('submit', formData.approveUserInfo)
      close()
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.el-date-editor.el-date-editor--date) {
  --el-date-editor-width: 190px;
  margin-right: 16px;
}
</style>
